/**

 * @Title: MapDataUtil.js

 * @Package dzdtApp

 * @Description: 针对此应用对数据访问更新服务API再次封装，方便调用

 * @author kimbo

 * @date 2014年12月8日 下午2:36:28

 * @version V1.0

 */
define(["MapData",
    "dojo/_base/declare",
    "dojo/_base/lang",
    "dojo/_base/array",
    "dojo/on",
    "dojo/topic",
    "dijit/registry",
    "esri/graphicsUtils",
    "dzdtApp/dzdtAppConfig",
    "dzdtApp/QueryLayerConfig",
    "esri/SpatialReference",
    "esri/graphic",
    "esri/geometry/Point",
    "esri/symbols/PictureMarkerSymbol",
    "esri/dijit/InfoWindow",
    "esri/InfoTemplate",
    "esri/geometry/Polyline",
    "esri/Color",
    "esri/symbols/SimpleLineSymbol",
    "dzdtApp/layout/mapLayout/MapManager",
    "esri/layers/GraphicsLayer"
], function (MapData, declare, lang, array, on, topic, registry, graphicsUtils, dzdtAppConfig, QueryLayerConfig, SpatialReference, Graphic, Point, PictureMarkerSymbol, InfoWindow, InfoTemplate, Polyline, Color, SimpleLineSymbol, MapManager, GraphicsLayer) {
    /**
     * 通过图层名称 找到QueryLayerConfig中对应的 groupId
     * 填写格式 表名:"groupid"
     *
     *  表名指的是数据库中真实的图层名称 groupid指的是QueryLayerConfig或者ZTLayerConfig中配置的groupId
     *
     */
    var layerNameLinkedGroupId = {
        "GIS_LX": "LAYERGROUP_DL",//路线
        "GIS_JSDJ": "LAYERGROUP_DL",//路线
        "GIS_XZQH": "LAYERGROUP_DL",//路线
        "GIS_QL": "LAYERGROUP_QL",//桥梁
        "GIS_SD": "LAYERGROUP_SD",//隧道
        "GIS_SFZ": "LAYERGROUP_SFZ",//收费站
        "GIS_FWQ": "LAYERGROUP_FWQ",//服务区
        "GIS_CRK": "LAYERGROUP_CRK",//出入口
        "GIS_ZCZ": "LAYERGROUP_ZCZ",//治超站
        "GIS_JTLGCZ": "LAYERGROUP_GCZ",//交通量观测站
        "GIS_KBQBB": "LAYERGROUP_KBQBB",//可变情报板
        "GIS_JKSSSB": "LAYERGROUP_JKSSSB",//监控设施设备
        "GIS_BZBP": "LAYERGROUP_BZBP",//标志标牌

        "GIS_KYZD": "LAYERGROUP_KYZD",//客运站点
        "GIS_HYZD": "LAYERGROUP_HYZD",//货运站点
        "GIS_CLWXQY": "LAYERGROUP_CLWXQY",//货运站点
        "GIS_JPJG": "LAYERGROUP_JPJG",//驾培机构
        "GIS_KYBX": "LAYERGROUP_KYBX",//客运班线
        "GIS_HYZZYTQY": "LAYERGROUP_HYZZYTQY",//货运装载源头企业
        "GIS_CGGGQCYYXL": "LAYERGROUP_CGGGQCYYXL",//常规公共汽车运营线路
        "GIS_CGGGQCYYZD": "LAYERGROUP_CGGGQCYYZD",// 常规公共汽车运营站点
        "GIS_GGDQCTCBYC": "LAYERGROUP_GGDQCTCBYC",//公共电汽车停车保养厂
        "GIS_CSGDJTYYXL": "LAYERGROUP_CSGDJTYYXL",//城市轨道交通运营线路
        "GIS_CSGDJTYYZD": "LAYERGROUP_CSGDJTYYZD",//城市轨道交通运营站点
        "GIS_CZCTKD": "LAYERGROUP_CZCTK",//出租车停靠点

        "GIS_GK": "LAYERGROUP_GK",//港口
        "GIS_ZDDK": "LAYERGROUP_ZDDK",//重点渡口
        "GIS_MT": "LAYERGROUP_MT",//  码头
        "GIS_NHHD": "LAYERGROUP_NHHD",//内河航道

        "GIS_ZFBM": "LAYERGROUP_ZFBM",//执法部门
        "GIS_GGP": "LAYERGROUP_GGP",// 广告牌
        "GIS_FGLBZ": "LAYERGROUP_FGLBZ",//非公路标志
        "GIS_DMGZW": "LAYERGROUP_DMGZW",//地面构筑物
        "GIS_KYGLSS": "LAYERGROUP_KYGLSS"//跨越公路设施
    };
    return {
        timer: null,
        fitExtent: function () {
            if (this.timer != null) {//防止重复调用多次
                window.clearTimeout(this.timer);
            }
            this.timer = window.setTimeout(function () {
//					console.info("fit extent!!!!");
                if (dzdtAppConfig.map.graphics.graphics.length > 0) {
                    //console.info(dzdtAppConfig.map.graphics.graphics);
                    var extent = graphicsUtils.graphicsExtent(dzdtAppConfig.map.graphics.graphics);
                    dzdtAppConfig.map.setExtent(extent * 1.5);
                }
            }, 1000);
        },
        query: function (params, isClear, symbol, infoTemplate) {
            var self = this;
            var defaultParams = {
                geoFormatType: 2//由于是ARCGIS平台所以采用JSON格式描述
            };
            var p = defaultParams;
            if (params) {
                p = $.extend(defaultParams, params);
            }
            //
            var mapData = new MapData(p);

            var graphics = [];
            mapData.sendRequest(function (data) {
                if (!data || data.Result == "Error") {
                    if (data) {
                        alert("查询数据出错：" + data["Msg"]);
                    } else {
                        alert("抱歉，查询数据出错！");
                    }
                    return;
                }
                var features = data.features;
                var layerName = data.layerName;
                console.info("layerNmae::", layerName);
                if (isClear != false) {
                    self.getTempLayer(layerName).clear();
                }
                for (var i = 0; i < features.length; i++) {
                    var geometryType = features[i].geometryType;
                    if (!geometryType) {
                        continue;
                    }
                    var graphic = null;
                    if (geometryType == "Point") {
                        ///console.info("features[i]:",features[i]);
                        graphic = self.drawPoint(layerName, features[i], symbol, infoTemplate, params);
                        graphics.push(graphic);
                    } else if (geometryType == "LineString") {
                        graphic = self.drawLine(layerName, features[i], symbol, infoTemplate, params);
                        graphic.params = params;
                        dzdtAppConfig.zhcqGraphic = graphic;//桩号查询Graphic
                    } else {
                        console.info("还未实现绘制'" + geometryType + "'类型的图元！");
                        break;
                    }
                }

                if (self.getTempLayer(layerName).graphics.length > 0) {
                    var extent = graphicsUtils.graphicsExtent(self.getTempLayer(layerName).graphics);
                    var extentAdjust = 0.3;
                    extent.update(extent.xmin - extentAdjust, extent.ymin - extentAdjust, extent.xmax + extentAdjust, extent.ymax + extentAdjust, new SpatialReference({wkid: 4326}));
                    dzdtAppConfig.map.setExtent(extent);
                }
                topic.publish("queryShapeComplated", {
                    "table": params.layerName,
                    "graphics": graphics
                });
//				 	self.fitExtent();
            });
        },
        getTempLayer: function (layerName) {
            var graphicLayerTemp = dzdtAppConfig.map.getLayer(layerName);
            if (!graphicLayerTemp) {
                graphicLayerTemp = new GraphicsLayer({
                    id: layerName,
                    visible: true
                });
                dzdtAppConfig.map.addLayer(graphicLayerTemp);
                var mapManager = dzdtAppConfig.mapManager;
                on(graphicLayerTemp, "mouse-over", lang.hitch(mapManager, mapManager.onGraphicMouseOver));
                on(graphicLayerTemp, "mouse-out", lang.hitch(mapManager, mapManager.onGraphicMouseOut));
            }
            return graphicLayerTemp;
        },
        drawPoint: function (layerName, point, symbol, infoTemplate, params) {
            if (!infoTemplate) {
                infoTemplate = this.getInfoTemplateByLayerName(layerName, point);
            }
            if (!symbol) {
                symbol = this.getSymbolByLayerName(layerName, point.attributes);
            }
            var mapPoint = new Point(point.geometry);
            var graphic = new Graphic(mapPoint, symbol, point.attributes);
            graphic.params = params;
            if (infoTemplate) {
                graphic.setInfoTemplate(infoTemplate);
            }
            this.getTempLayer(layerName).add(graphic);
            return graphic;
        },
        drawLine: function (layerName, line, symbol, infoTemplate, params) {
            var self = this;
            var mapLine = new Polyline(line.geometry);
            if (!infoTemplate) {
                infoTemplate = self.getInfoTemplateByLayerName(layerName, line);
            }
            if (!symbol) {
                symbol = new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, new Color([0, 0, 255]), 3);
            }
            var graphic = new Graphic(mapLine, symbol, line.attributes);
            graphic.params = params;
            if (infoTemplate) {
                graphic.setInfoTemplate(infoTemplate);
            }
            this.getTempLayer(layerName).add(graphic);
            return graphic;
        },
        getGroupIdByLayerName: function (layerName) {
            var groupId = layerNameLinkedGroupId[layerName];
            if (!groupId) {
                groupId = layerNameLinkedGroupId[layerName.toUpperCase()];
            }
            if (!groupId) {
                groupId = layerNameLinkedGroupId[layerName.toLowerCase()];
            }
            if (!groupId) {
                console.error("没有找到图层'" + layerName + "'对应的groupId，请增加配置！");
            }
            return groupId;
        },
        getInfoTemplateByLayerName: function (layerName, feature) {
            var groupId = this.getGroupIdByLayerName(layerName);
            if (groupId) {
//					 console.info(layerName+"->"+groupId,feature);
                var contentHTML = QueryLayerConfig.buildFeatureTipHTMLByGroupId(groupId, feature);
                var infoTemplate = new InfoTemplate("详细信息", contentHTML);
                return infoTemplate;
            } else {
                return null;
            }
        },
        getSymbolByLayerName: function (layerName, attributes) {
            var symbols = null, symbol = null, attValue = null;
            var groupId = this.getGroupIdByLayerName(layerName);
            if (groupId) {
                symbols = QueryLayerConfig.getSymbolsByGroupId(groupId);
                if (symbols.symbolFilterField) {
                    attValue = attributes[symbols.symbolFilterField];
                    attValue = attValue + "";
                    symbol = symbols[attValue]();
                } else {
                    symbol = symbols["default"]();
                }
                if (!symbol) {
                    symbol = symbols["default"]();
                }
            }
            if (!symbols) {
                symbols = new PictureMarkerSymbol("dzdtApp/resources/image/zh.png", 20, 20);
            }
            return symbol;
        },
        clearPartalGraphic: function (params) {
            var graphics = [];
            var graphicsLayerIdsLen = dzdtAppConfig.map.graphicsLayerIds.length;
            for (var m = 0; m < graphicsLayerIdsLen; m++) {
                var graphicLayerID = dzdtAppConfig.map.graphicsLayerIds[m];
                if (graphicLayerID === params.layerName) {
                    var garphicLayerTemp = dzdtAppConfig.map.getLayer(graphicLayerID);
                    array.forEach(garphicLayerTemp.graphics, function (graphic) {
                        if (graphic.params.where === params.where) {
                            graphics.push(graphic);
                        }
                    });
                    var len = graphics.length;
                    for (var i = 0; i < len; i++) {
                        var gp = graphics[i];
                        garphicLayerTemp.remove(gp);
                    }
                }
            }
        },
        //高亮和还原高亮  显示某个graphic
        hightlightGraphic: function (/*graphic所在的graphiclayer的ID*/layerName, /*ojb{attribeteName:"",attributeValue}*/where, isInitial) {
            var graphicLayer = this.getTempLayer(layerName);
            //[{"attrName": "桥梁编码", "attrValue": "G5610126L4580"}]
            if (graphicLayer) {
                var arrtName = where.attrName;
                var groupID = this.getGroupIdByLayerName(layerName);
                var attrOriginalName = QueryLayerConfig.getFieldEnglishLabel(groupID, arrtName);
                var attrValue = where.attrValue;
                var len = graphicLayer.graphics.length;
                var graphic = null;
                for (var i = 0; i < len; i++) {
                    graphic = graphicLayer.graphics[i];
                    var geoType = graphic.geometry.type.toLowerCase();
                    if (graphic.isZoom) {
                        if (geoType == "point") {
                            graphic.symbol.setHeight(graphic.symbol.height / 1.2);
                            graphic.symbol.setWidth(graphic.symbol.width / 1.2);
                            graphic.draw();
                        } else {
                            graphic.symbol.setWidth(graphic.symbol.width / 1.2);
                            graphic.draw();
                        }
                        graphic.isZoom = false;
                    }
                }
                for (var i = 0; i < len; i++) {
                    graphic = graphicLayer.graphics[i];
                    var geoType = graphic.geometry.type.toLowerCase();
                    var attributes = graphic.attributes;
                    if (attributes && attributes[attrOriginalName]) {
                        if (attrValue === attributes[attrOriginalName]) {
                            if (this.hightlightGraphic.zoomValue == attrValue) {
                                this.hightlightGraphic.zoomValue = "";
                                break;
                            }
                            if (geoType == "point") {
                                graphic.symbol.setHeight(graphic.symbol.height * 1.2);
                                graphic.symbol.setWidth(graphic.symbol.width * 1.2);
                                graphic.draw();
                            } else {
                                graphic.symbol.setWidth(graphic.symbol.width * 1.2);
                                graphic.draw();
                            }
                            graphic.isZoom = true;
                            this.hightlightGraphic.zoomValue = attrValue;
                            break;
                        }
                    }

                }
                return graphic;
            }
        }
    }
});